#include "StdAfx.h"
#include "Weather.h"
#include "../kernel.h"
#include <math.h>

extern Kernel* g_kernel;

#define TIME g_kernel->GetTime()

///** Hour Date */
//const int DAWN_TO_DUSK =120;
///** Max Darkness */
//const int MAX_DARK = 20;

Weather::Weather(void)
{
    m_rain = false;
    m_fog  = false;
    m_lap  = true;
    m_nextDayTime = 120.0f;
    // next possible lightining
    m_nextLightning = 0.0f;
    m_type  = LT_NOTHING;

    rain_f.Set( this );
    rainTime_f.Set( this );
 //   g_kernel->GetConsole()->AddCommand( &rain_f, "g_rain" );
    g_kernel->GetConsole()->AddCommand( &rainTime_f, "g_raintime" );
    g_kernel->GetCvars()->RegisterCvar( "g_weather_time", "120", 120.0f, CVAR_SAVE );
    g_kernel->GetCvars()->RegisterCvar( "g_weather_max_dark", "20", 20.0f, CVAR_SAVE );
}

/** SEt the fog color */
void Weather::SetFogColor( int r, int g, int b, int a)
{
    m_fColor.SetData( r, g, b, a );
}

/** Get the Time of day in hours */
float Weather::GetTimeOfDay() 
{ 
    float nextDayTime = g_kernel->GetCvars()->GetFloatValue( "g_weather_time");
    float maxDark = g_kernel->GetCvars()->GetFloatValue( "g_weather_max_dark");
    if ( TIME > m_nextLightning )
    {
        float time = ( (int)(TIME/1000) % (int)nextDayTime  );
        if ( time >= nextDayTime-1 )
        {
            m_nextLightning = TIME + 1000;
            m_lap = !m_lap;
        }
        else if( m_lap )
        {
            return (nextDayTime - time) + maxDark;

        }
        return time + maxDark;
    }
    return (m_lap ? nextDayTime  : 0) + maxDark;

}

/** Check Lightning */
int Weather::CheckLightning()
{
    if ( IsRaining() && TIME > m_nextLightning )
    {   
        m_type = rand() / 100;
         
        switch( m_type )
        {
            case LT_SMALL:  m_nextLightning = TIME + 350; // small
                break;
            //case LT_MED:    m_nextLightning = TIME + 590; // med
            //    break;
            //case LT_BIG:    m_nextLightning = TIME + 910; // big
            //    break;
            default:
                m_type = LT_NOTHING;
        }
        return m_type;
    }
    return m_type;
}

Weather::~Weather(void)
{
  //  g_kernel->GetConsole()->RemoveCommand("g_rain");
    g_kernel->GetConsole()->RemoveCommand("g_raintime");
}


/*---------------------------
    Weather function
----------------------------*/

void Rain_f::Exec(std::string &s) 
{
    if ( m_weather )
    {
        float v = (float)atof(s.c_str());
        bool b = (v > 0);
        m_weather->EnableRain( b );
    }
}

void RainTime_f::Exec(std::string &s) 
{
    if ( m_weather )
    {
        float v = (float)atof(s.c_str());
        m_weather->SetNextDayTime( v );
    }
}


